package org.liurb.springboot.starter.redis.conf.gson;


import jakarta.annotation.Resource;
import org.liurb.springboot.starter.gson.serializer.GsonRedisSerializer;
import org.liurb.springboot.starter.redis.conf.base.BaseLettuceConnectionFactory;
import org.liurb.springboot.starter.redis.conf.base.RedisConfigProperties;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;


/**
 * 公共redis配置类
 *
 * 加载配置，实例化连接池，并提供获取RedisTemplate方法
 * 使用gson序列化
 *
 * @Author Liurb
 * @Date 2022/11/30
 */
public class BackendGsonRedisConfig extends BaseLettuceConnectionFactory {

    @Resource
    RedisConfigProperties redisConfigProperties;

    /**
     * 获取redis模板实例
     *
     * @param database 数据库
     * @return
     */
    public RedisTemplate<String, Object> getRedisTemplate(int database) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(getLettuceConnectionFactory(database));

        redisTemplate.setKeySerializer(new StringRedisSerializer());

        GsonRedisSerializer gsonRedisSerializer = new GsonRedisSerializer(Object.class);

        redisTemplate.setValueSerializer(gsonRedisSerializer);

        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(gsonRedisSerializer);

        return redisTemplate;
    }

    @Override
    public RedisConfigProperties getRedisConfigProperties() {

        return redisConfigProperties;
    }
}
